﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using BusinessEntity;
using BusinessRule;
using BusinessRule.Organization;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Nacos.AspNetCore;
using ProjectManApi.Extensions;
using ProjectManApi.mmm;

namespace ProjectManApi.Controllers
{
    public class UsersController : MvcControllerBase
    {

        private readonly IOperator _operator;
        private readonly IHttpContextAccessor _iHttpContextAccessor;

        private readonly JWTConfig jwtConfig;


        //添加Nacos 中间件
        private readonly INacosServerManager _serverManager;

        public UsersController(IOperator ioperator, IHttpContextAccessor iHttpContextAccessor, IOptions<JWTConfig> ijwtConfig, INacosServerManager iserverManager)
        {
            _operator = ioperator;
            _iHttpContextAccessor = iHttpContextAccessor;

            jwtConfig = ijwtConfig.Value;

            _serverManager = iserverManager;
        }

        #region 快速登录类
        public class AuthoritiesItem
        {
            /// <summary>
            /// 
            /// </summary>
            public string authority { get; set; }
        }

        public class User_info
        {
            /// <summary>
            /// 
            /// </summary>
            public string password { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string username { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<AuthoritiesItem> authorities { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string accountNonExpired { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string accountNonLocked { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string credentialsNonExpired { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string enabled { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string id { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string deptId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string phone { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string avatar { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int tenantId { get; set; }
        }

        public class RootLogin
        {
            /// <summary>
            /// 
            /// </summary>
            public string access_token { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string token_type { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string refresh_token { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int expires_in { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string scope { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string license { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string active { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public User_info user_info { get; set; }

            public string code { get; set; }
            public string msg { get; set; }
            //public string data { get; set; }
     

        }
        #endregion


        [HttpPost]
        [AllowAnonymous]
        //public async Task<IActionResult> Login([FromForm]string username, [FromForm]string password)
        public async Task<IActionResult> LoginDSZ([FromForm] string username, [FromForm] string password)
        {
            //http://{{BASE_URL}}/auth/oauth/token?grant_type=password


            string key = "pigxpigxpigxpigx";
            string result1 = AESEncrypt.AesEncrypt(password, key);
            _logger.Info("sssssssss");
            var baseUrl = _serverManager.GetServerAsync("ic-auth").GetAwaiter().GetResult();
            _logger.Info(baseUrl);
            if (string.IsNullOrWhiteSpace(baseUrl))
            {
                //await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.exception, info = "授权服务节点全挂了" });
                return Fail("");
            }

            //var url = $"{baseUrl}/oauth/check_token";
            //http://{{BASE_URL}}/auth/oauth/token?grant_type=password

            var url = $"{baseUrl}/auth/oauth/token?grant_type=password";

            using (HttpClient client = new HttpClient())
            {
                string clientInfo = "test:test";
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                client.DefaultRequestHeaders.Add("Authorization", "Basic " + clientInfo);
                //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
                //client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;");

                //http://{{BASE_URL}}/auth/oauth/token?grant_type=password
                //http://{{BASE_URL}}/oauth/check_token
                //http://118.190.140.38:3000/token/login

                //url = url.Replace("172.31.162.64:3000", "118.190.140.38:5052");
                url = BusinessRule.JavaApi.GetIpAddress10(baseUrl);
                

                //client.BaseAddress = new Uri(url);
                //设置请求体中的内容，并以post的方式请求
                //token=697d2737-fe50-49b2-82c8-33ff2932d28a
                //var response = await client.PostAsync(url, new StringContent("token=697d2737-fe50-49b2-82c8-33ff2932d28a"));

                var data = Encoding.UTF8.GetBytes("username="+ username + "&password="+ result1 + "&grant_type=password&scope=server");
                var content = new ByteArrayContent(data);
                content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

                var response = await client.PostAsync(url, content);


                //获取请求到数据，并转化为字符串
                var result = response.Content.ReadAsStringAsync().Result;
                _logger.Info(result);
                var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<RootLogin>(result);// result.ToJson();

                if (!string.IsNullOrWhiteSpace(Jresult.code))
                {
                    //await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = Jresult.error_description });
                    return Fail(Jresult.msg);
                }

                if (null == Jresult.access_token)
                {
                    //await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = Jresult.error_description });
                    return Fail("Token 获取失败"); ;
                }

               

                return Success(Jresult);
            }

        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="username">账号</param>
        /// <param name="password">密码</param>
        /// <returns>登录令牌信息</returns>
        [HttpPost]
        [AllowAnonymous]
        //public async Task<IActionResult> Login([FromForm]string username, [FromForm]string password)
        public async Task<IActionResult> Login([FromForm]string username, [FromForm]string password)
        {
            #region 写入日志
            LogEntity logEntity = new LogEntity();
            logEntity.F_CategoryId = 1;
            logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
            logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.ApiLogin);
            logEntity.F_OperateAccount = username;
            logEntity.F_OperateUserId = username;
            logEntity.F_IPAddress = _iHttpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            logEntity.F_Module = ConfigHelper.GetConfig().SoftName;
            #endregion

            #region 内部账户验证

            //AUserEntity userEntity1 = await UserRule.GetEntity();
            AUserEntity userEntity = await UserRule.GetEntityByAccount(username);
            if (userEntity == null)
            {
                logEntity.F_ExecuteResult = 0;
                logEntity.F_ExecuteResultJson = "没有此账号!";
                await LogRule.Write(logEntity);
                return Fail("账号密码不匹配");
            }

            if (userEntity.F_EnabledMark != 1)
            {
                logEntity.F_ExecuteResult = 0;
                logEntity.F_ExecuteResultJson = "账户被系统锁定,请联系管理员!";
                await LogRule.Write(logEntity);
                return Fail("账户被系统锁定,请联系管理员!");
            }
            bool isOk = UserRule.IsPasswordOk(userEntity.Pwd, password, userEntity.F_Secretkey);


            if (!isOk)//登录失败
            {
                logEntity.F_ExecuteResult = 0;
                logEntity.F_ExecuteResultJson = "账号密码不匹配";
                await LogRule.Write(logEntity);
                return Fail("账号密码不匹配");
            }
            else
            {
                logEntity.F_ExecuteResult = 1;
                logEntity.F_ExecuteResultJson = "登录成功";
                await LogRule.Write(logEntity);
                string token = _operator.EncodeToken(userEntity.Id, userEntity.Name, username, jwtConfig);
                return Success(token);
            }
            #endregion
        }
    }
}